package com.basics.common.utils;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.*;

public class PayUtils {
    public PayUtils() {
    }

    public static Logger getLogger() {
        Logger logger = LoggerFactory.getLogger("wxpay java sdk");
        return logger;
    }

    public static String createSign(SortedMap<String, Object> sortedMap, String key, PrivateKey merchantPrivateKey) throws Exception {
        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<String, Object>> entries = sortedMap.entrySet();
        Iterator iterator = entries.iterator();

        while(iterator.hasNext()) {
            Map.Entry<String, Object> next = (Map.Entry)iterator.next();
            if (null != next.getValue() && StringUtils.isNotBlank(String.valueOf(next.getValue())) && !StringUtils.equals("key", (CharSequence)next.getKey()) && !StringUtils.equals("singn", (CharSequence)next.getKey())) {
                sb.append((String)next.getKey() + "=" + next.getValue() + "&");
            }
        }

        sb.append("key=").append(key);
        String stmpKey = sb.toString();
        String sign = MD5(stmpKey).toUpperCase();
        return sign;
    }

    public static boolean isCreateSign(SortedMap<String, Object> sortedMap, String key, PrivateKey merchantPrivateKey) throws Exception {
        String sign = createSign(sortedMap, key, merchantPrivateKey);
        String beCheckedSign = (String)sortedMap.get("sign");
        return beCheckedSign.equals(sign);
    }

    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    public static String MD5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            byte[] var4 = array;
            int var5 = array.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                byte item = var4[var6];
                sb.append(Integer.toHexString(item & 255 | 256).substring(1, 3));
            }

            return sb.toString().toUpperCase();
        } catch (Exception var8) {
            return null;
        }
    }

    public static String sign(String content, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(content.getBytes());
        return Base64.getEncoder().encodeToString(signature.sign());
    }
}
